<template>
  <div class="file-preview" ref="filePreviewRef">
    <FilePreviewHeader 
      :fileName="fileName" 
      :fileType="fileType"
      :fileUrl="fileUrl"
      :isFullscreen="isFullscreen"
      @back="$emit('back')"
      @download="downloadFile"
      @toggleFullscreen="toggleFullscreen"
    />
    
    <div class="preview-content" ref="previewContentRef">
      <!-- 加载中状态 -->
      <FilePreviewLoading v-if="loading" />
      
      <!-- 错误状态 -->
      <FilePreviewError 
        v-else-if="error" 
        :error="error"
        @retry="loadFile" 
      />
      
      <!-- Office文档预览 (PDF, Word, PPT, Excel) -->
      <FilePreviewOffice 
        v-else-if="isOfficeDocument" 
        :officeViewerUrl="officeViewerUrl"
        :fileUrl="fileUrl"
        :fileName="fileName"
        :fileContent="fileContent"
        @download="downloadFile"
      />
      
      <!-- Markdown预览 -->
      <FilePreviewMarkdown 
        v-else-if="fileType === 'markdown'" 
        :fileContent="fileContent"
        :fileUrl="fileUrl"
        :editorId="editorId"
      />
      
      <!-- TXT文件预览 -->
      <FilePreviewTxt
        v-else-if="fileType === 'txt'"
        :fileUrl="fileUrl"
      />
      
      <!-- HTML预览 -->
      <FilePreviewHtml 
        v-else-if="fileType === 'html'" 
        :fileUrl="fileUrl" 
      />
      
      <!-- 图片预览 -->
      <FilePreviewImage 
        v-else-if="fileType === 'image'" 
        :fileUrl="fileUrl" 
      />
      
      <!-- 视频预览 -->
      <FilePreviewVideo 
        v-else-if="fileType === 'video'" 
        :fileUrl="fileUrl"
        :fileName="fileName"
        :getFileExtension="getFileExtension"
      />
      
      <!-- 不支持的文件类型 -->
      <FilePreviewUnsupported v-else />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { usePermissionStore } from '../../store';
import { useRoute, useRouter } from 'vue-router';
import { parseCompactLink } from '../../utils/crypto';

// 导入子组件
import FilePreviewHeader from './components/FilePreviewHeader.vue';
import FilePreviewLoading from './components/FilePreviewLoading.vue';
import FilePreviewError from './components/FilePreviewError.vue';
import FilePreviewOffice from './components/FilePreviewOffice.vue';
import FilePreviewMarkdown from './components/FilePreviewMarkdown.vue';
import FilePreviewTxt from './components/FilePreviewTxt.vue';
import FilePreviewHtml from './components/FilePreviewHtml.vue';
import FilePreviewImage from './components/FilePreviewImage.vue';
import FilePreviewVideo from './components/FilePreviewVideo.vue';
import FilePreviewUnsupported from './components/FilePreviewUnsupported.vue';

// 获取路由参数
const route = useRoute();
const router = useRouter();

const props = defineProps({
  fileUrl: {
    type: String,
    default: ''
  },
  fileName: {
    type: String,
    default: '未命名文件'
  },
  fileType: {
    type: String,
    default: '' // document, markdown, video, image, html, presentation, spreadsheet, txt
  },
  shortCode: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['back']);

// 状态管理
const loading = ref(true);
const error = ref(null);
const fileContent = ref('');
const editorId = ref(`preview-md-${Date.now()}`);
const permissionStore = usePermissionStore();
const previewContentRef = ref(null);
const filePreviewRef = ref(null);
const isFullscreen = ref(false);

// 短链接解析后的文件信息
const fileInfoFromShortLink = ref(null);

// 处理短链接
const processShortLink = async () => {
  if (!props.shortCode) return false;
  
  try {
    loading.value = true;
    error.value = null;
    
    console.log('处理短链接:', props.shortCode);
    
    // 解析短链接
    const fileInfo = parseCompactLink(props.shortCode);
    console.log('短链接解析结果:', fileInfo);
    
    if (!fileInfo || !fileInfo.url) {
      error.value = '无效的分享链接';
      loading.value = false;
      return false;
    }
    
    // 设置文件信息
    fileInfoFromShortLink.value = fileInfo;
    return true;
  } catch (err) {
    console.error('处理短链接失败:', err);
    error.value = '无效的分享链接';
    loading.value = false;
    return false;
  }
};

// 从路由获取文件信息
const fileUrlFromRoute = computed(() => {
  // 优先使用短链接解析的URL
  if (fileInfoFromShortLink.value?.url) {
    return fileInfoFromShortLink.value.url;
  }
  return route.query.url || props.fileUrl || '';
});

const fileNameFromRoute = computed(() => {
  // 优先使用短链接解析的文件名
  if (fileInfoFromShortLink.value?.name) {
    return fileInfoFromShortLink.value.name;
  }
  return route.query.name || props.fileName || '未命名文件';
});

const fileTypeFromRoute = computed(() => {
  // 优先使用短链接解析的文件类型
  if (fileInfoFromShortLink.value?.type) {
    return fileInfoFromShortLink.value.type;
  }
  
  // 如果路由或props提供了文件类型，则使用提供的类型
  if (route.query.type || props.fileType) {
    return route.query.type || props.fileType;
  }
  
  // 否则根据文件名推断类型
  return inferFileType(fileNameFromRoute.value);
});

// 实际使用的文件URL、文件名和文件类型
const fileUrl = computed(() => fileUrlFromRoute.value);
const fileName = computed(() => fileNameFromRoute.value);
const fileType = computed(() => fileTypeFromRoute.value);

// 根据文件名推断文件类型
const inferFileType = (fileName) => {
  if (!fileName) return 'document';
  
  const extension = getFileExtension(fileName);
  
  // 文档类型
  if (['pdf', 'doc', 'docx'].includes(extension)) {
    return 'document';
  }
  
  // 演示文稿
  if (['ppt', 'pptx'].includes(extension)) {
    return 'presentation';
  }
  
  // 电子表格
  if (['xls', 'xlsx', 'csv'].includes(extension)) {
    return 'spreadsheet';
  }
  
  // Markdown
  if (['md', 'markdown'].includes(extension)) {
    return 'markdown';
  }
  
  // 文本文件
  if (['txt', 'log', 'ini', 'json', 'xml', 'yml', 'yaml'].includes(extension)) {
    return 'txt';
  }
  
  // HTML
  if (['html', 'htm'].includes(extension)) {
    return 'html';
  }
  
  // 图片
  if (['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'bmp'].includes(extension)) {
    return 'image';
  }
  
  // 视频
  if (['mp4', 'webm', 'ogg', 'mov', 'avi', 'flv', 'wmv', 'm3u8'].includes(extension)) {
    return 'video';
  }
  
  // 默认为文档
  return 'document';
};

// 判断是否为Office文档
const isOfficeDocument = computed(() => {
  // 检查文件类型
  if (['document', 'presentation', 'spreadsheet', 'pdf', 'word', 'powerpoint', 'excel'].includes(fileType.value)) {
    return true;
  }
  
  // 如果类型不明确，通过文件扩展名判断
  const extension = getFileExtension(fileName.value).toLowerCase();
  const officeExtensions = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'];
  
  return officeExtensions.includes(extension);
});

// Office文档查看器URL
const officeViewerUrl = computed(() => {
  if (!isOfficeDocument.value) return '';
  
  // 获取文件扩展名
  const extension = getFileExtension(fileName.value).toLowerCase();
  
  // 对于PDF，直接使用浏览器内置查看器
  if (extension === 'pdf' || fileType.value === 'pdf') {
    return fileUrl.value;
  }
  
  // 对于其他Office文档，使用Microsoft Office Online Viewer
  const encodedUrl = encodeURIComponent(fileUrl.value);
  return `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`;
});

// 获取文件扩展名
const getFileExtension = (fileName) => {
  if (!fileName || typeof fileName !== 'string') return '';
  const parts = fileName.split('.');
  return parts.length > 1 ? parts.pop().toLowerCase() : '';
};

// 加载文件内容
const loadFile = async () => {
  if (!fileUrl.value) {
    error.value = '无效的文件URL';
    loading.value = false;
    
    // 避免在控制台显示错误
    console.warn('无效的文件URL，fileUrl为空');
    return;
  }
  
  loading.value = true;
  error.value = null;
  
  try {
    console.log('加载文件类型:', fileType.value, '文件URL:', fileUrl.value);
    
    // 根据文件类型加载不同的内容
    if (fileType.value === 'txt') {
      await loadTextFile();
    } else if (fileType.value === 'markdown') {
      // Markdown文件由FilePreviewMarkdown组件自行处理
      loading.value = false;
    } else {
      // 其他类型通过组件直接处理，无需额外加载
      loading.value = false;
    }
  } catch (err) {
    console.error('加载文件失败:', err);
    error.value = '文件加载失败，请检查文件路径或格式是否正确';
  } finally {
    loading.value = false;
  }
};

// 加载文本文件（Markdown或TXT）
const loadTextFile = async () => {
  try {
    // 尝试使用标准模式
    const response = await fetch(fileUrl.value);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    fileContent.value = await response.text();
  } catch (error) {
    console.error('标准模式加载文本文件失败:', error);
    
    try {
      // 尝试使用no-cors模式
      console.log('尝试使用no-cors模式加载文件');
      const response = await fetch(fileUrl.value, { mode: 'no-cors' });
      fileContent.value = await response.text();
    } catch (nocorsError) {
      console.error('no-cors模式加载文本文件也失败:', nocorsError);
      
      // 如果是CORS错误，设置一个友好的错误信息
      if (error.toString().includes('CORS')) {
        fileContent.value = `# 无法加载文件内容\n\n由于跨域限制，无法直接加载文件内容。请尝试以下方法：\n\n1. 下载文件后在本地查看\n2. 联系管理员配置正确的CORS头\n\n文件路径: ${fileUrl.value}`;
      } else {
        throw error;
      }
    }
  }
};

// 下载文件
const downloadFile = () => {
  if (!permissionStore.canDownload) {
    ElMessage({
      type: 'warning',
      message: permissionStore.downloadDisabledMessage || '您没有下载权限'
    });
    return;
  }
  
  try {
    const link = document.createElement('a');
    link.href = fileUrl.value;
    link.download = fileName.value;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage({
      type: 'success',
      message: '文件下载已开始'
    });
  } catch (err) {
    console.error('下载文件失败:', err);
    ElMessage({
      type: 'error',
      message: '文件下载失败，请重试'
    });
  }
};

// 切换全屏模式
const toggleFullscreen = () => {
  if (!isFullscreen.value) {
    // 进入全屏模式
    enterFullscreen();
  } else {
    // 退出全屏模式
    exitFullscreen();
  }
};

// 进入全屏模式
const enterFullscreen = () => {
  const element = filePreviewRef.value;
  if (!element) return;
  
  try {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) { /* Firefox */
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) { /* IE/Edge */
      element.msRequestFullscreen();
    }
  } catch (error) {
    console.error('进入全屏模式失败:', error);
    ElMessage.warning('进入全屏模式失败');
  }
};

// 退出全屏模式
const exitFullscreen = () => {
  try {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) { /* Firefox */
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) { /* Chrome, Safari & Opera */
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) { /* IE/Edge */
      document.msExitFullscreen();
    }
  } catch (error) {
    console.error('退出全屏模式失败:', error);
    ElMessage.warning('退出全屏模式失败');
  }
};

// 监听文件URL或文件类型变化
watch([fileUrl, fileType], ([newUrl, newType]) => {
  if (newUrl && !props.shortCode) {
    loadFile();
  }
}, { immediate: false });

// 监听全屏状态变化
const handleFullscreenChange = () => {
  // 更新全屏状态
  isFullscreen.value = !!document.fullscreenElement || 
                      !!document.mozFullScreenElement || 
                      !!document.webkitFullscreenElement || 
                      !!document.msFullscreenElement;
  
  console.log('全屏状态变化:', isFullscreen.value);
};

// 组件挂载时添加事件监听
onMounted(async () => {
  // 添加全屏状态变化监听器
  document.addEventListener('fullscreenchange', handleFullscreenChange);
  document.addEventListener('mozfullscreenchange', handleFullscreenChange);
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.addEventListener('MSFullscreenChange', handleFullscreenChange);
  
  // 处理短链接
  if (props.shortCode) {
    const success = await processShortLink();
    if (success) {
      // 短链接处理成功后加载文件
      loadFile();
    }
  } else {
    // 正常加载文件
    loadFile();
  }
});

// 组件卸载时移除监听器
onUnmounted(() => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange);
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange);
});
</script>

<style scoped>
.file-preview {
  width: 100%;
  height: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.preview-content {
  flex: 1;
  overflow: auto;
  min-height: 100vh;
}

/* 全屏模式样式 */
.preview-content:fullscreen {
  background-color: white;
  padding: 20px;
  overflow: auto;
}

.preview-content:fullscreen .office-container,
.preview-content:fullscreen .markdown-container,
.preview-content:fullscreen .html-container,
.preview-content:fullscreen .image-container,
.preview-content:fullscreen .video-container,
.preview-content:fullscreen .txt-container {
  height: 100vh;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .preview-content {
    min-height: 80vh;
  }
}
</style> 